/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/* eslint-disable import/no-extraneous-dependencies */
/**
 * 巴枪扫描记录通用页面
 *  */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import {
  debounce,
  // isEqual, isEmpty
} from 'lodash';
import { Form, message } from 'antd';
import moment from 'moment';
import InfoCheck from '@/components/InfoCheck';
import { getLStorage } from '@/utils/utils';
import PropTypes from 'prop-types';
import ScanRecord from '@/components/ScanRecord';
import styles from '../style.less';

const wayBillTypeMap = {
  send: 6,
  arrive: 5,
  delivery: 2,
  sign: 3,
  error: 4,
};

const searchIntercept = (addressId = [], shop_id) => {
  const cacheAddressId = getLStorage(shop_id);
  if (addressId.length < 3) {
    message.error('请先选择具体地区');
    return true;
  }
  if (!cacheAddressId) {
    message.error('请点击切换地区后查询');
    return true;
  }
  return false;
};

@connect(({ allocation, loading, setting, router, user }, { type }) => ({
  options: setting.options,
  allocation,
  query_params: allocation[`query_${type}`],
  tableData: allocation[`${type}ScanTableData`],
  brandType: allocation[`${type}Brand`],
  router,
  loading: loading.effects['allocation/getScanSearch'],
  userInfo: user.currentUser.user_info,
}))
@Form.create()
export default class GunScanRecordTemplate extends PureComponent {
  constructor(props) {
    super(props);
    const { phone, gp_area_ids = [], area_ids } = this.props.userInfo || {};
    const isCompany = area_ids == '*';
    const cacheAreaId = getLStorage(`KB_GP_AREA_${phone}`);
    const area_id = gp_area_ids.includes(cacheAreaId)
      ? cacheAreaId
      : isCompany
        ? '0'
        : gp_area_ids[0];
    this.state = {
      isZyAccount: false,
      area_id,
    };
  }

  // 点击查询
  getSendSearch = debounce(
    props => {
      const { isZyAccount, shop_id } = this.state;
      const { dispatch, addressId = [], type } = this.props;
      const { phone, gp_area_ids = [], area_ids } = this.props.userInfo || {};

      const isCompany = area_ids == '*';
      const cacheAreaId = getLStorage(`KB_GP_AREA_${phone}`);
      const area_id = gp_area_ids.includes(cacheAreaId)
        ? cacheAreaId
        : isCompany
          ? '0'
          : gp_area_ids[0];
      if (isZyAccount && searchIntercept(addressId, shop_id)) {
        return;
      }
      if (!props) return;
      dispatch({
        type: 'allocation/save',
        payload: {
          [`${type}ScanTableData`]: {},
        },
      });
      dispatch({
        type: 'allocation/getScanSearch',
        payload: {
          page: 1,
          waybill_type: wayBillTypeMap[type],
          area_id,
          ...props,
        },
      });
      dispatch({
        type: 'allocation/save',
        payload: {
          [`query_${type}`]: props,
        },
      });
    },
    500,
    {
      leading: true,
      trailing: false,
    },
  );

  // 获取网点信息
  getBranchInfo({ waybill_type, branch_id, area_id }) {
    const { dispatch } = this.props;
    dispatch({
      type: 'allocation/getBranchInfo',
      payload: {
        brand: 'all',
        waybill_type,
        branch_id,
        area_id,
      },
    });
  }

  handleInfoReady = data => {
    if (!data.name) {
      message.warn('公司信息未完善！');
      return;
    }
    const {
      dispatch,
      options: { key },
      addressId = [],
      router,
      type,
      brandType,
    } = this.props;
    const { location = {} } = router;
    const {
      query: {
        brand,
        start_scan_time,
        end_scan_time,
        cm_phone,
        send_status,
        dispatch_phone,
        waybill_no,
      } = {},
      hash,
    } = location;
    const { user_info = {} } = data;
    const { shop_id } = user_info;
    const isZyAccount = key === 'post' || key === 'yjy';
    const isHashEqual = hash.includes(type);
    const { area_id } = this.state;
    if (isZyAccount) {
      if (addressId && addressId.length === 3) {
        this.getBranchInfo({ waybill_type: type, branch_id: addressId[2] });
      }
    } else {
      this.getBranchInfo({ waybill_type: type, area_id });
    }
    this.setState({
      brand: brand || brandType,
      isZyAccount,
      shop_id,
    });
    dispatch({
      type: 'allocation/save',
      payload: {
        isZyAccount,
        addressId,
        [`${type}Brand`]: brand || brandType || 'all',
      },
    });
    // 判断路由与传入的type是否一致，防止tab切换请求数据
    if (brand && isHashEqual) {
      if (isZyAccount && searchIntercept(addressId, shop_id)) return;
      dispatch({
        type: 'allocation/save',
        payload: {
          [`${type}ScanTableData`]: {},
          [`${type}BrandCode`]: 'all',
        },
      });
      dispatch({
        type: 'allocation/getScanSearch',
        payload: {
          page: 1,
          waybill_type: wayBillTypeMap[type],
          start_scan_time:
            moment(start_scan_time).format('YYYY-MM-DD 00:00:00') ||
            moment().format('YYYY-MM-DD 00:00:00'),
          send_status: send_status || '3',
          end_scan_time:
            moment(end_scan_time).format('YYYY-MM-DD 23:59:59') ||
            moment().format('YYYY-MM-DD 23:59:59'),
          courier: cm_phone || '',
          cm_phone: cm_phone || '',
          waybill_no,
          brand,
          branch_code: 'all',
          branch_id: isZyAccount ? [...addressId].pop() : '',
          dispatch_phone,
          area_id,
        },
      });
      dispatch({
        type: 'allocation/save',
        payload: {
          [`query_${type}`]: {
            start_scan_time:
              moment(start_scan_time).format('YYYY-MM-DD 00:00:00') ||
              moment().format('YYYY-MM-DD 00:00:00'),
            send_status: send_status || '3',
            end_scan_time:
              moment(end_scan_time).format('YYYY-MM-DD 23:59:59') ||
              moment().format('YYYY-MM-DD 23:59:59'),
            courier: cm_phone || '',
            cm_phone: cm_phone || '',
            waybill_no,
            brand,
            branch_code: 'all',
            branch_id: isZyAccount ? [...addressId].pop() : '',
            dispatch_phone,
          },
        },
      });
    }
  };

  // 翻页
  paginationChange(e) {
    const { dispatch, type, query_params } = this.props;
    dispatch({
      type: 'allocation/save',
      payload: {
        [`${type}ScanTableData`]: {},
      },
    });
    dispatch({
      type: 'allocation/getScanSearch',
      payload: {
        page: e,
        waybill_type: wayBillTypeMap[type],
        ...query_params,
      },
    });
  }

  // 导出
  // exportExcel(props) {
  //   const { query_params, tableData } = this.props;
  //   if (isEmpty(query_params) && isEmpty(tableData)) {
  //     message.warning('无数据可导出，请先查询');
  //     return false;
  //   }
  //   const { list } = tableData;
  //   if ((list && list.length === 0) || !list) {
  //     message.warning('无数据可导出');
  //     return false;
  //   }
  //   if (isEqual(props, query_params)) {
  //     return true;
  //   }
  //   message.warning('查询条件已改变，请先查询后再导出');
  //   return false;
  // }

  render() {
    const { loading, router, type, tableData = {} } = this.props;
    const {
      location: { query },
    } = router;
    const { page, total, list = [] } = tableData;
    const { brand } = this.state;

    return (
      <div>
        <InfoCheck onReady={this.handleInfoReady} />
        <div className={styles.ScanRecord}>
          <div className="form">
            <ScanRecord
              search={props => this.getSendSearch(props)}
              dataSource={list}
              pagination={{ size: 20, count: total, page }}
              paginationChange={e => this.paginationChange(e)}
              loading={loading}
              type={type}
              // exportExcel={par => this.exportExcel(par)}
              brand={brand}
              queryData={query}
            />
          </div>
        </div>
      </div>
    );
  }
}

GunScanRecordTemplate.propTypes = {
  type: PropTypes.oneOf(['delivery', 'arrive', 'send', 'sign', 'error']).isRequired,
};
